import os

from django.http import FileResponse, Http404
from django.shortcuts import render

# Create your views here.
from xinload.settings import BASE_DIR


def index(request):
    return render(request, "index.html", {"downloads": [
        {
            "name": "shadowrocket",
            "url": "https://gitee.com/xhw/xinload/raw/master/public/res/ipa_10.206.plist"
        },
    ]})


def file_response_download(request):
    file_path = os.path.join(BASE_DIR, 'public', 'media')
    file_path = file_path + request.path
    ext = os.path.basename(file_path).split('.')[-1].lower()
    if ext not in ['py', 'db', 'sqlite3']:
        response = FileResponse(open(file_path, 'rb'))
        response['content_type'] = "application/octet-stream"
        response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path)
        return response
    else:
        raise Http404

# # Create your views here.
# def mobileconfig(request):
#     file_name = "1234.mobileconfig"
#     file_path = os.path.join(getfiledir(None), file_name)  # 下载文件的绝对路径

#     if not os.path.isfile(file_path):  # 判断下载文件是否存在
#         return HttpResponse("Sorry but Not Found the File")

#     try:
#         # 设置响应头
#         # StreamingHttpResponse将文件内容进行流式传输，数据量大可以用这个方法
#         response = StreamingHttpResponse(file_iterator(file_path))
#         # 以流的形式下载文件,这样可以实现任意格式的文件下载
#         response['Content-Type'] = 'application/octet-stream'
#         # Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
#         response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)
#     except Exception as e:
#         return HttpResponse("Sorry but Not Found the File")

#     return response
